package com.lizemin.springaspect.interceptor;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author lzm
 * @date 2025/3/31 21:37
 * @description 缓存请求体，实现重复读取请求体的功能
 *
 * 由于getInputStream和getReader方法都是用来获取请求体的方法，所以这两个方法我们都要重写，将其改成
 * 从缓存中读取请求体
 */
public class RepeatableRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 缓存请求体
     */
    private final byte[] body;

    public RepeatableRequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            // 获取请求体
            ServletInputStream inputStream = request.getInputStream();
            // 将请求体缓存到body中
            body = StreamUtils.copyToByteArray(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 从缓存中读取请求体
     */
    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }

    /**
     * 从缓存中读取请求体
     */
    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    public String getRequestBody(){
        return new String(body, StandardCharsets.UTF_8);
    }

}
